/**
 * 统一响应处理中间件
 * 确保所有响应都符合项目统一的格式规范
 *
 * @param {Error} err - 错误对象
 * @param {Request} req - 请求对象
 * @param {Response} res - 响应对象
 * @param {Function} next - 下一个中间件函数
 */

const { logError, LOG_TYPES } = require('../library/logger.js');

// 全局错误处理中间件
const ErrorTypes = {
    VALIDATION: 'VALIDATION',     // 参数验证错误
    AUTHENTICATION: 'AUTH',       // 认证错误
    AUTHORIZATION: 'AUTHZ',       // 权限错误
    NOT_FOUND: 'NOT_FOUND',       // 资源不存在
    CONFLICT: 'CONFLICT',         // 资源冲突
    DATABASE: 'DATABASE',         // 数据库错误
    EXTERNAL: 'EXTERNAL',         // 外部服务错误
    INTERNAL: 'INTERNAL'          // 内部服务器错误
};

// 统一错误响应格式
function createErrorResponse(error, type = ErrorTypes.INTERNAL) {
    const errorMap = {
        [ErrorTypes.VALIDATION]: { code: 400, message: '参数验证失败' },
        [ErrorTypes.AUTHENTICATION]: { code: 401, message: '认证失败' },
        [ErrorTypes.AUTHORIZATION]: { code: 403, message: '权限不足' },
        [ErrorTypes.NOT_FOUND]: { code: 404, message: '资源不存在' },
        [ErrorTypes.CONFLICT]: { code: 409, message: '资源冲突' },
        [ErrorTypes.DATABASE]: { code: 500, message: '数据库操作失败' },
        [ErrorTypes.EXTERNAL]: { code: 502, message: '外部服务异常' },
        [ErrorTypes.INTERNAL]: { code: 500, message: '服务器内部错误' }
    };

    const errorInfo = errorMap[type];

    return {
        success: false,
        code: errorInfo.code,
        message: errorInfo.message,
        error: error.message,
        timestamp: Date.now()
    };
}

// 统一成功响应格式
function createSuccessResponse(data = {}, message = '操作成功', code = 200) {
    return {
        success: true,
        code: code,
        message: message,
        data: data,
        timestamp: Date.now()
    };
}

// 全局错误处理中间件
function globalErrorHandler(err, req, res, next) {
    // 记录错误日志
    console.error('全局错误处理:', {
        error: err.message,
        stack: err.stack,
        url: req.url,
        method: req.method,
        body: req.body,
        query: req.query,
        timestamp: new Date().toISOString()
    });

    // 根据错误类型返回相应的响应
    let errorType = ErrorTypes.INTERNAL;
    let statusCode = 500;

    // 判断错误类型
    if (err.name === 'ValidationError' || err.message.includes('验证')) {
        errorType = ErrorTypes.VALIDATION;
        statusCode = 400;
    } else if (err.name === 'UnauthorizedError' || err.message.includes('Token') || err.message.includes('认证')) {
        errorType = ErrorTypes.AUTHENTICATION;
        statusCode = 401;
    } else if (err.name === 'ForbiddenError' || err.message.includes('权限')) {
        errorType = ErrorTypes.AUTHORIZATION;
        statusCode = 403;
    } else if (err.name === 'NotFoundError' || err.message.includes('不存在')) {
        errorType = ErrorTypes.NOT_FOUND;
        statusCode = 404;
    } else if (err.name === 'ConflictError' || err.message.includes('已存在') || err.message.includes('冲突')) {
        errorType = ErrorTypes.CONFLICT;
        statusCode = 409;
    } else if (err.name === 'SequelizeError' || err.message.includes('数据库')) {
        errorType = ErrorTypes.DATABASE;
        statusCode = 500;
    } else if (err.message.includes('微信') || err.message.includes('外部')) {
        errorType = ErrorTypes.EXTERNAL;
        statusCode = 502;
    }

    // 返回统一格式的错误响应
    res.status(statusCode).json(createErrorResponse(err, errorType));
}

// 404错误处理
function notFoundHandler(req, res, next) {
    const error = new Error(`路由 ${req.method} ${req.url} 不存在`);
    error.name = 'NotFoundError';
    next(error);
}

module.exports = {
    globalErrorHandler,
    notFoundHandler,
    ErrorTypes,
    createErrorResponse,
    createSuccessResponse
};